
import React, { Component, createRef } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import MotionLayout from '@/layouts/MotionLayout';
import { InfoListByQuery, InfoTypeList, InfoEdit, InfoAdd, InfoDel, InfoSingle, InfoEditMulti, InfoCopy } from "@/services/info";
import { ReadConfig, writeConfig, } from "@/services/homeSet";

import {
  PlusOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
  FormOutlined,
  DeleteOutlined,
  HomeOutlined,
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  CopyOutlined,

} from '@ant-design/icons';
import { Button, Space, Dropdown, Menu, message, Switch, Cascader, DatePicker, Modal, Input } from 'antd';

const arrayToTree = require('array-to-tree');
import moment from "moment"
import UpdateForm from './components/UpdateForm';
import CreateForm from './components/CreateForm';

const actionRef = createRef();
import { HomeList } from "@/utils/config.js"


class Info extends Component {
  constructor(props) {
    super(props)
    this.state = {
      options: [],
      SwitchIsEnable: false,
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
      typeList: [],
      CascaderOptions: [],
      Edit: -1,
      orderNum: -1,

    }
    InfoTypeList().then(({ result, success }) => {
      if (success) {
        const typeList = result.arr.map(item => ({ ...item, value: item.id.toString(), label: item.infoTypeName, fid: item.fid.toString() }))
        const options = arrayToTree(typeList, { rootID: "0", parentProperty: "fid", customID: "value", childrenProperty: "children" })
        this.setState({ options, typeList, })
      }
    })
  }
  /**
 * 更新节点
 * @param fields
 */
  async handleUpdate(fields) {
    const hide = message.loading('正在更新');
    try {
      const res = await InfoEdit({
        ...fields,
      });
      hide();
      if (!res.success) {
        message.error(`更新失败，${res.result}`);
        return false;
      }
      message.success('更新成功');
      return true;
    } catch (error) {
      hide();
      message.error(`更新异常，${error}`);
      return false;
    }
  };
  /**
 * 添加节点
 * @param fields
 */
  async handleAdd(fields) {
    const hide = message.loading('正在添加');
    try {
      const res = await InfoAdd({ ...fields });
      hide();
      if (!res.success) {
        message.error(`添加失败，${res.result}`);
        return false;
      }
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error(`添加异常，${error}`);
      return false;
    }
  };
  /**
 *  删除节点
 * @param idList
 */
  async handleRemove(idList) {
    const hide = message.loading('正在删除');
    try {
      const res = await InfoDel(idList);
      hide();
      if (!res.success) {
        message.error(`删除失败，${res.result}`);
        return false;
      }
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error(`删除异常，${error}`);
      return false;
    }
  };
  /**
   *  添加到首页
   * @param selectedRows
   */
  async handleHome(params) {
    const cname = HomeList.find(item => item.name == params.key).cname;
    const hide = message.loading(`正在添加到${cname}`);
    try {
      const resRead = await ReadConfig({ name: params.key });

      // if (!resRead.success) {
      //   message.error(`查询失败，${resRead.result}`);
      //   hide();
      //   return false;
      // }
      const addObj = {
        title: params.title,
        content: params.bodySub,
        time: moment(params.createTime).format("YYYY-MM-DD"),
        href: `/detail?id=${params.id}`,
        src: params.cover,
        isEnable: false,
        orderNum: "0",
      }

      const json = [addObj, ...JSON.parse(resRead.rescode == 200 ? resRead.result : "[]")];
      const resWrite = await writeConfig({ name: params.key, jsonString: JSON.stringify(json) });
      if (!resWrite.success) {
        message.error(`写入失败，${resWrite.result}`);
        hide();
        return false;
      }
      hide();
      message.success(`添加到${cname}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`异常，${error}`);
      return false;
    }
  };

  async getDataSource(params) {
    const { result, success } = await InfoListByQuery({
      ...params,
      page: params.current,
      limit: params.pageSize,
      infoTypeIds: params.infoTypeId ? params.infoTypeId[params.infoTypeId.length - 1] : null,
      betweenTime: params.betweenTime ? `${params.betweenTime[0].format("YYYY-MM-DD HH:mm:ss")},${params.betweenTime[1].format("YYYY-MM-DD HH:mm:ss")}` : null,
    })
    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }
    return {
      data: result.arr,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '序号',
        dataIndex: 'index',
        valueType: 'indexBorder',
      },
      {
        title: '标题',
        dataIndex: 'title',
      },
      {
        title: '栏目',
        dataIndex: 'infoTypeName',
        hideInSearch: true,
      },
      {
        title: '列表顺序',
        dataIndex: 'orderNum',
        hideInSearch: true,
        render: (_, row) => {
          return (<div onClick={() => {
            this.setState({
              Edit: row.id,
              orderNum: row.orderNum,
            })
          }}>{this.state.Edit != row.id ? row.orderNum :
            <div><Input value={this.state.orderNum} onChange={(e) => {

              this.setState({
                orderNum: parseInt(e.target.value),
              })
            }} size="small" style={{ width: 40 }} /><Button
                onClick={(e) => {
                  e.stopPropagation();
                  this.setState({
                    Edit: -1,
                  })
                }}
                size="small" icon={<CloseOutlined />} /><Button
                onClick={async (e) => {
                  e.stopPropagation();
                  const success = await this.handleUpdate({
                    id: row.id,
                    orderNum: this.state.orderNum,
                  });
                  this.setState({
                    Edit: -1,
                  })
                  if (!success) {
                    return;
                  }
                  if (!actionRef.current) {
                    return;
                  }
                  actionRef.current.reload();
                }}
                size="small" icon={<CheckOutlined />} /></div>
            }</div>);
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        hideInSearch: true,
        renderText: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '是否可用',
        dataIndex: 'isEnable',
        hideInSearch: true,
        render: (_, row) => {
          return (<Switch disabled={this.state.SwitchIsEnable}
            checkedChildren={"启用"} unCheckedChildren={"禁用"}
            onChange={async (isEnable) => {
              const success = await this.handleUpdate({
                id: row.id,
                isEnable: isEnable,
              });
              if (!success) {
                return;
              }
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            checked={_}
          // defaultChecked={_}
          />)
        }
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space size="small">
            <Dropdown
              overlay={
                <Menu
                  onClick={async ({ key }) => {
                    await this.handleHome({ key, ...row, })

                  }}
                >
                  {
                    HomeList.map(item => <Menu.Item key={item.name}>{item.cname}</Menu.Item>)
                  }
                </Menu>
              }
            >
              <Button
                onClick={() => {
                }}
                size="small" type="default" icon={<HomeOutlined />} ></Button>
            </Dropdown>
            <Button
              title="编辑"
              onClick={async () => {
                // const selectRow = {
                //   ...row,
                //   pubTime: moment(row.createTime).format("YYYY-MM-DD HH:mm:ss"),
                //   infoType: row.treeIds ? [...JSON.parse(row.treeIds), row.infoTypeId.toString()] : [],
                // }
                // this.setState({
                //   updateModalVisible: true,
                //   // selectRow,
                // })
                const hide = message.loading('正在载入');
                try {
                  const res = await InfoSingle({ id: row.id });
                  hide();
                  if (!res.success) {
                    message.error(`载入失败，${res.result}`);
                    return;
                  }
                  const fobj = this.state.typeList.find(item => item.id == res.result.infoTypeId)
                  const selectRow = {
                    ...res.result,
                    pubTime: moment(res.result.createTime).format("YYYY-MM-DD HH:mm:ss"),
                    infoType: fobj ? [...JSON.parse(fobj.treeIds), fobj.id.toString()] : [],
                  };
                  this.setState({
                    updateModalVisible: true,
                    selectRow,
                  })
                  message.success('载入成功');
                } catch (error) {
                  hide();
                  message.error(`载入异常，${error}`);
                  return;
                }

              }}
              size="small" type="primary" icon={<FormOutlined />}></Button>
            <Button
              title="删除"
              onClick={() => {
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      "id": [
                        row.id
                      ]
                    };
                    const success = await this.handleRemove(idList);
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
            <Button
              title="复制"
              onClick={() => {
                Modal.confirm({
                  title: '是否确认复制该条信息?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {

                    const hide = message.loading('正在复制');
                    try {
                      const res = await InfoCopy({ id: row.id });
                      hide();
                      if (!res.success) {
                        message.error(`复制失败，${res.result}`);
                        return;
                      }
                      message.success('复制成功');
                      if (!actionRef.current) {
                        return;
                      }
                      actionRef.current.reload();
                    } catch (error) {
                      hide();
                      message.error(`操作异常，${error}`);
                    }
                  },
                });
              }}
              size="small" type="default" icon={<CopyOutlined />}></Button>
            <a title="预览" href={`${process.env.NODE_ENV === 'development' ? `http://localhost:5793` : ""}/web/dist/detail?id=${row.id}`} target="_blank" className="ant-btn ant-btn-sm ant-btn-sm ant-btn-icon-only"><EyeOutlined style={{ position: "relative", left: -4 }} /></a>
          </Space>
        ),
      },
      {
        title: '类型',
        dataIndex: 'remark',
        hideInTable: true,
      },
      {
        title: '是否可用',
        dataIndex: 'isEnable',
        hideInTable: true,
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Processing',
          },
        },
      },
      {
        title: '栏目',
        dataIndex: 'infoTypeId',
        order: 10,
        hideInTable: true,
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<Cascader options={this.state.options} placeholder="选择栏目" />)
        }
      },
      {
        title: '时间段',
        dataIndex: 'betweenTime',
        hideInTable: true,
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<DatePicker.RangePicker />)
        }
      },
    ];
  }
  render() {
    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <ProTable
            actionRef={actionRef}
            headerTitle=""
            rowKey="id"
            params={{}}
            request={async (params) => this.getDataSource(params)}
            columns={this.createColumns()}
            rowSelection={{}}
            pagination={{
              pageSize: 10,
            }}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => [
              selectedRowKeys && selectedRowKeys.length > 0 && (<span style={{ marginRight: 100 }}><Cascader onChange={(value) => this.setState({ CascaderOptions: value })} options={this.state.options} placeholder="将栏目移动到" /> <Button
                onClick={async () => {
                  // const infoTypeypeId = this.state.CascaderOptions[]
                  if (this.state.CascaderOptions.length == 0) {
                    return;
                  }
                  // InfoEditMulti
                  const infoTypeId = Number(this.state.CascaderOptions[this.state.CascaderOptions.length - 1]);
                  const { success, result } = await InfoEditMulti({
                    idList: selectedRowKeys,
                    infoTypeId,
                  });
                  if (!success) {
                    message.success(`更新失败，${result}`);
                    return;
                  }
                  message.success('更新成功');
                  this.setState({ CascaderOptions: [] })
                  if (!actionRef.current) {
                    return;
                  }
                  actionRef.current.reload();
                  // console.log(selectedRowKeys,infoTypeypeId)
                }}
              >确定</Button></span>),
              <Button type="primary" onClick={() => this.setState({ createModalVisible: true })}>
                <PlusOutlined /> 新建
                      </Button>,
              selectedRowKeys && selectedRowKeys.length > 0 && (
                <Dropdown
                  overlay={
                    <Menu
                      onClick={async e => {
                        if (e.key === 'remove') {
                          const idList = {
                            "id": selectedRowKeys
                          };
                          Modal.confirm({
                            title: '是否确认删除?',
                            icon: <ExclamationCircleOutlined />,
                            onOk: async () => {
                              const success = await this.handleRemove(idList);
                              if (!success) {
                                return;
                              }
                              if (!actionRef.current) {
                                return;
                              }
                              actionRef.current.reload();
                            },
                          });
                        }
                      }}
                      selectedKeys={[]}
                    >
                      <Menu.Item key="remove">批量删除</Menu.Item>
                      <Menu.Item key="approval">批量审批</Menu.Item>
                    </Menu>
                  }
                >
                  <Button>
                    批量操作 <DownOutlined />
                  </Button>
                </Dropdown>
              ),


            ]}
          />
        </MotionLayout>
        <UpdateForm
          onCancel={() => this.setState({ updateModalVisible: false, selectRow: {} })}
          updateModalVisible={this.state.updateModalVisible}
          row={this.state.selectRow}
          onSubmit={async fieldsValues => {
            const fields = {
              ...fieldsValues,
              infoTypeId: Number(fieldsValues.infoType[fieldsValues.infoType.length - 1]),
              orderNum: Number(fieldsValues.orderNum),
              viewNum: Number(fieldsValues.viewNum),
              createTime: moment(fieldsValues.pubTime).format("YYYY-MM-DD HH:mm:ss"),
              id: this.state.selectRow.id,
            }
            const success = await this.handleUpdate(fields);
            if (!success) {
              return;
            }
            this.setState({
              updateModalVisible: false,
            })
            if (!actionRef.current) {
              return;
            }
            actionRef.current.reload();
          }}
        />
        <CreateForm
          onCancel={() => this.setState({ createModalVisible: false })}
          createModalVisible={this.state.createModalVisible}
          onSubmit={async fieldsValues => {
            const fields = {
              ...fieldsValues,
              infoTypeId: Number(fieldsValues.infoType[fieldsValues.infoType.length - 1]),
              orderNum: Number(fieldsValues.orderNum),
              viewNum: Number(fieldsValues.viewNum),
              createTime: moment(fieldsValues.pubTime).format("YYYY-MM-DD HH:mm:ss"),
            }
            const success = await this.handleAdd(fields);
            if (!success) {
              return;
            }
            this.setState({
              createModalVisible: false,
            })
            if (!actionRef.current) {
              return;
            }
            actionRef.current.reload();
          }}
        />
      </PageHeaderWrapper>
    )
  }
}
export default Info
